package com.mspbots.usermanage.model;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.mspbots.core.account.model.TenantAccount
 *
 * @author Jason
 * @date 2019/12/10
 **/
@Data
@NoArgsConstructor
public class TenantAccount implements Serializable {

    private Long id;
    private Long tenantId;
    private String username;
    private String password;
    private String email;
    private Long avatar;
    private Long departmentId;
    private LocalDateTime updateTime;
    private LocalDateTime createTime;
    private LocalDateTime lastLoginTime;
    private Boolean lockFlag;
    private Boolean delFlag;
    private List<String> authorities;

    @Builder
    public TenantAccount(Long id, Long tenantId, String username,
                         String password, String email, Long avatar,
                         Long departmentId, LocalDateTime updateTime,
                         LocalDateTime createTime, LocalDateTime lastLoginTime,
                         Boolean lockFlag, Boolean delFlag) {
        this.id = id;
        this.tenantId = tenantId;
        this.username = username;
        this.password = password;
        this.email = email;
        this.avatar = avatar;
        this.departmentId = departmentId;
        this.updateTime = updateTime;
        this.createTime = createTime;
        this.lastLoginTime = lastLoginTime;
        this.lockFlag = lockFlag;
        this.delFlag = delFlag;
    }

    private static List<String> sortAuthorities(Collection<String> authorities) {
        Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
        List<String> sortedAuthorities = new ArrayList<>(authorities);
        return sortedAuthorities.parallelStream().sorted().map(role -> "ROLE_" + role).collect(Collectors.toList());
    }


    public void setAuthorities(List<String> authorities) {
        this.authorities = sortAuthorities(authorities);
    }

}
